import pandas as pd
import requests
import json
import re

def get_coze_xhs_data(api_token, workflow_id='7529822902763159571', file_path='小红书.xlsx', sheet_name='Sheet1'):
    def get_random_xhs_row(file_path=file_path, sheet_name=sheet_name):
        df = pd.read_excel(file_path, sheet_name=sheet_name)
        df_xhs = df[df['type'] == 'xhs']
        if df_xhs.empty:
            return None, None
        row = df_xhs.sample(n=1).iloc[0]
        return row['count'], row['content']

    def call_coze_workflow(subject, word_count, api_key, workflow_id):
        url = 'https://api.coze.cn/v1/workflow/run'
        headers = {
            'Authorization': f'Bearer {api_key}',
            'Content-Type': 'application/json'
        }
        data = {
            'workflow_id': workflow_id,
            'parameters': {
                'subject': subject,
                'word_count': str(word_count)
            }
        }
        response = requests.post(url, headers=headers, data=json.dumps(data))
        if response.status_code == 200:
            return response.json()
        else:
            print('调用Coze API失败:', response.status_code, response.text)
            return None

    count, content = get_random_xhs_row()
    if not count or not content:
        return None
    result = call_coze_workflow(content, count, api_token, workflow_id)
    if result and result.get('code') == 0 and 'data' in result:
        try:
            data_json = json.loads(result['data'])
            img_url = data_json.get('output', '')
            img_response = requests.get(img_url)
            with open('header.jpg', 'wb') as f:
                f.write(img_response.content)
            output1 = data_json.get('output1', '')
            # 提取标题
            title_section = re.search(r'## 标题\n(.*?)\n\n', output1, re.DOTALL)
            title_list = []
            if title_section:
                titles = title_section.group(1).strip().split('\n')
                for t in titles:
                    m = re.match(r'\d+\.\s*(.*)', t)
                    if m:
                        title_list.append(m.group(1))
            # 提取正文
            body_section = re.search(r'## 正文\n(.*?)\n\n## 标签', output1, re.DOTALL)
            body = body_section.group(1).strip() if body_section else ''
            # 提取标签
            tag_section = re.search(r'## 标签\n[#\*]*(.*)', output1, re.DOTALL)
            tag_list = []
            if tag_section:
                tags = tag_section.group(1).strip()
                tag_list = [tag.strip().strip('*') for tag in re.split(r'#', tags) if tag.strip()]
            result_dict = {
                "title": title_list[0] if title_list else '',
                "content": body,
                "tags": tag_list
            }
            return result_dict
        except json.JSONDecodeError as e:
            print(f"解析data字段失败: {e}")
            return None
    else:
        print("接口调用失败或返回格式异常")
        return None
    
if __name__ == "__main__":
    api_token = "pat_Qv3BnaJLl4NpTMvjrQNoJyV2gz1s1aAsO7r51vYqAWy2x92ccM8g0mu0sGTTfc2e"
    myxhs_data = get_coze_xhs_data(api_token)
    print(myxhs_data)